<script setup>
import api from '@/api/index.js'
import { message } from 'ant-design-vue'
import { computed, ref, h, provide } from 'vue'
import MyTable from '@/components/MyTable/MyTable.vue'
import { Modal } from 'ant-design-vue'
import { useUserStore } from '@/stores/modules/user.js'

const userStore = useUserStore()
const dicts = computed(() => userStore.dicts)
const props = defineProps({
  // 表格数据总条数
  total: { type: Number, default: 0 },
  // 表格当前页码
  pageNum: { type: Number, default: 1 }
})
const emits = defineEmits(['edit', 'reload', 'pageChange'])
// 分页参数
const pagination = computed(() => ({
  total: props.total,
  showSizeChanger: false,
  current: props.pageNum,
  onChange: (e) => {
    emits('pageChange', e)
  }
}))
// 表格列配置
const columns = ref([
  { ellipsis: true, title: '所属字典', key: 'type' },
  { ellipsis: true, title: '字典名', dataIndex: 'constLabel', key: 'constLabel' },
  { ellipsis: true, title: '字典值', dataIndex: 'constValue', key: 'constValue' },
  { ellipsis: true, title: '创建时间', dataIndex: 'createAt', key: 'createAt' },
  { ellipsis: true, title: '操作', key: 'set' }
])
// 编辑数据
const edit = (item) => {
  emits('edit', item)
}
// 编辑成功修改缓存
const changeDictFromPinia = (params) => {
  let newDict = dicts.value[params.type]
  let delItem = newDict.findIndex((e) => e.id === params.id)
  newDict.splice(delItem, 1)
  const newDicts = { ...dicts.value, [params.type]: newDict }
  userStore.setDicts(newDicts)
}
//删除数据
const del = (item) => {
  Modal.warning({
    title: '删除字典',
    content: h(
      'span',
      {},
      '是否删除字典数据：',
      h('span', { style: { color: '#09c690' } }, item.constLabel)
    ),
    okText: '删除',
    okCancel: true,
    okButtonProps: { type: 'primary', danger: true },
    cancelButtonProps: { type: 'primary' },
    cancelText: '取消',
    onOk: async () => {
      await api.delDict({ id: item.id })
      changeDictFromPinia(item)
      message.success('删除成功')
      emits('reload')
      return Promise.resolve()
    },
    onCancel: () => {
      message.success('取消删除')
      return Promise.resolve()
    }
  })
}
provide('columns', columns.value)

const dictList = ref(window.config.dictList)
const getName = (key) => {
  const item = dictList.value.find((item) => item?.value === key)
  return item?.label
}
</script>

<template>
  <MyTable :pagination="pagination" :scroll="{ y: 'calc(100vh - 383px)' }">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'type'">
        {{ getName(record.type) }}
      </template>
      <template v-if="column.key === 'set'">
        <!-- <AButton type="link" @click="edit(record)">编辑</AButton> -->
        <!-- <AButton type="link" class="com-delbtn" @click="del(record)">删除</AButton> -->
      </template>
    </template>
  </MyTable>
</template>